package com.shuhua.common.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.shuhua.common.annotation.IgnoreResponseAdvice;
import com.shuhua.common.result.Result;
import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 全局响应结果处理
 */
@RestControllerAdvice(basePackages = {"com.shuhua"})
public class ResponseResultAdvice implements ResponseBodyAdvice<Object> {
    
    private final ObjectMapper objectMapper;
    
    public ResponseResultAdvice(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }
    
    /**
     * 判断是否需要处理返回值
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 如果已经是Result类型，则不需要处理
        if (returnType.getParameterType().equals(Result.class)) {
            return false;
        }
        
        // 检查是否标记了忽略注解
        if (returnType.getDeclaringClass().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        
        if (returnType.getMethod() != null && returnType.getMethod().isAnnotationPresent(IgnoreResponseAdvice.class)) {
            return false;
        }
        
        return true;
    }
    
    /**
     * 处理返回值
     */
    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
                                  Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                  ServerHttpRequest request, ServerHttpResponse response) {
        // 处理返回值为String的情况
        if (body instanceof String) {
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return objectMapper.writeValueAsString(Result.success(body));
        }
        
        // 处理返回值为null的情况
        if (body == null) {
            return Result.success();
        }
        
        // 处理其他情况
        return Result.success(body);
    }
} 